import { defineStore } from 'pinia'
import { ref } from 'vue'
import { 
  getUserNotifications, 
  markNotificationAsRead,
  markAllNotificationsAsRead, 
  getUnreadNotificationCount 
} from '@/api/notification'

export const useNotificationStore = defineStore('notification', () => {
  const notifications = ref([])
  const unreadCount = ref(0)
  const isLoading = ref(false)

  // 获取通知列表
  const fetchNotifications = async (params = {}) => {
    try {
      isLoading.value = true
      const response = await getUserNotifications(params)
      notifications.value = response.data.items
      return response
    } catch (error) {
      console.error('获取通知列表失败', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 获取未读通知数量
  const fetchUnreadCount = async () => {
    try {
      const response = await getUnreadNotificationCount()
      unreadCount.value = response.data.count
      return response
    } catch (error) {
      console.error('获取未读通知数量失败', error)
      throw error
    }
  }

  // 标记通知为已读
  const markAsRead = async (notificationId) => {
    try {
      const response = await markNotificationAsRead(notificationId)
      // 更新本地状态
      const notification = notifications.value.find(n => n.id === notificationId)
      if (notification && !notification.read) {
        notification.read = true
        unreadCount.value = Math.max(0, unreadCount.value - 1)
      }
      return response
    } catch (error) {
      console.error('标记通知已读失败', error)
      throw error
    }
  }

  // 标记所有通知为已读
  const markAllAsRead = async () => {
    try {
      const response = await markAllNotificationsAsRead()
      // 更新本地状态
      notifications.value.forEach(notification => {
        notification.read = true
      })
      unreadCount.value = 0
      return response
    } catch (error) {
      console.error('标记所有通知已读失败', error)
      throw error
    }
  }

  return {
    notifications,
    unreadCount,
    isLoading,
    fetchNotifications,
    fetchUnreadCount,
    markAsRead,
    markAllAsRead
  }
})